package com.coocaa.ops.admin.v1.timedtask.biz;

import com.coocaa.ops.admin.v1.timedtask.mapper.ITimedTaskInfoMapper;
import com.coocaa.ops.common.core.base.BaseBizImpl;
import com.coocaa.ops.common.core.base.enums.ResourceStatusEnums;
import com.coocaa.ops.common.core.base.mybatis.QueryTemplate;
import com.coocaa.ops.common.core.base.validator.ResourceTypeValidator;
import com.coocaa.ops.common.core.biz.timedtask.entity.TimedTaskInfoEntity;
import com.coocaa.ops.common.tool.date.DateUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author bijiahao
 * @date : 2018/9/25.
 * @description
 */
@Service
public class TimedTaskBizImpl extends BaseBizImpl<ITimedTaskInfoMapper, TimedTaskInfoEntity> implements ITimedTaskBiz {

    @Override
    public boolean isCanCancelTimedTask(Integer resourceId, String type) {
        Integer count = null;
        if (ResourceTypeValidator.isTab(type)) {
            count = getMapper().getTabNotOnlineDataCount(resourceId);
        } else if (ResourceTypeValidator.isPanel(type)) {
            count = getMapper().getPanelNotOnlineDataCount(resourceId);
        }
        return count == null || count == 0;
    }

    @Override
    public TimedTaskInfoEntity add(TimedTaskInfoEntity entity) {
        Date date = DateUtil.getCurDate();
        entity.setCreateTime(date);
        entity.setLastUpdateDate(date);
        getMapper().insert(entity);
        return entity;
    }

    @Override
    public void updateStatus(Integer id, Integer status) {
        TimedTaskInfoEntity update = new TimedTaskInfoEntity();
        update.setId(id);
        update.setStatus(status);
        this.updateById(update);
    }

    @Override
    public TimedTaskInfoEntity queryOneTimedTask(String timedType, Integer resourceId, String resourceType) {
        QueryTemplate<TimedTaskInfoEntity> wrapper = new QueryTemplate<>();
        wrapper.eq("status", ResourceStatusEnums.ON_LINE.getStatus())
                .eq("timed_type", timedType)
                .eq("resource_id", resourceId)
                .eq("resource_type", resourceType)
        ;
        List<TimedTaskInfoEntity> list = getMapper().selectList(wrapper);
        return CollectionUtils.isNotEmpty(list) ? list.get(0) : null;
    }

    @Override
    public Integer countTask(String timedType, Integer resourceId, String resourceType) {
        QueryTemplate<TimedTaskInfoEntity> wrapper = new QueryTemplate<>();
        wrapper.eq("timed_type", timedType)
                .eq("resource_id", resourceId)
                .eq("resource_type", resourceType)
        ;
        Integer count = this.getMapper().selectCount(wrapper);
        return null != count ? count : 0;
    }
}
